package org.jeecg.modules.qy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhyd.oauth.utils.StringUtils;
import me.zhyd.oauth.utils.UuidUtils;
import org.apache.commons.collections.CollectionUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.qy.entity.QyAccount;
import org.jeecg.modules.qy.entity.QyCommodity;
import org.jeecg.modules.qy.entity.QyCommodityAttribute;
import org.jeecg.modules.qy.entity.vo.SourceDataVo;
import org.jeecg.modules.qy.entity.vo.VisitUserVo;
import org.jeecg.modules.qy.mapper.QyCommodityMapper;
import org.jeecg.modules.qy.service.IQyAccountService;
import org.jeecg.modules.qy.service.IQyCommodityAttributeService;
import org.jeecg.modules.qy.service.IQyCommodityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @Description: 商品表
 * @Author: jeecg-boot
 * @Date:   2021-03-10
 * @Version: V1.0
 */
@Service
public class QyCommodityServiceImpl extends ServiceImpl<QyCommodityMapper, QyCommodity> implements IQyCommodityService {

    /**
     *商品属性
     */
    @Autowired
    private IQyCommodityAttributeService qyCommodityAttributeService;

    @Autowired
    private IQyAccountService accountService;


    public long countByCommodityType(int commodityType,String companyId){
        QueryWrapper<QyCommodity> qe = new QueryWrapper<>();
        qe.eq("company_id",companyId);
        qe.eq("commodity_type",commodityType);
        qe.eq("commodity_status",1);
        return count(qe);
    }

    public List<QyCommodity> findByCompanyId(String companyId){
        QueryWrapper<QyCommodity> qe = new QueryWrapper<>();
        qe.eq("company_id",companyId);
        qe.eq("commodity_status",1);
        qe.orderByDesc("create_time");
        return list(qe);
    }

    @Override
    public Result<String> saveComodity(QyCommodity commodity,String companyId){
        List<QyCommodityAttribute> buteList = commodity.getCommodityAttributeList();
        if(CollectionUtils.isEmpty(buteList)){
            return Result.ERROR("提交信息不全");
        }
        List<QyCommodity> ststuaList = list(new QueryWrapper<QyCommodity>().eq("company_id",companyId).eq("commodity_status",0));
        if(CollectionUtils.isNotEmpty(ststuaList)){
            return Result.ERROR("存在未完成商品");
        }
        QyAccount account = accountService.getByCompanyId(companyId);
        if(commodity.getCommodityType()==1){
            if(account.getCommoditySurplusNum()<1){
                return Result.ERROR("一物一码剩余商品个数未0");
            }
        }else{
            if(account.getMuchCommoditySurplusNum()<1){
                return Result.ERROR("N物一码剩余商品个数未0");
            }
        }

        commodity.setId(UuidUtils.getUUID());
        if(commodity.getCommodityType()==1){
            //一物一码
            commodity.setOneCodeNum(10000);
            commodity.setOneCodeTotalNum(10000);
        }else{
            commodity.setMuchCodeNum(1);
            commodity.setMuchCodeTotalNum(1);
        }
        commodity.setCompanyId(companyId);
        save(commodity);

        //保存商品属性
        for(int a=0;a<buteList.size();a++){
            QyCommodityAttribute bute = buteList.get(a);
            bute.setCommodityId(commodity.getId());
            bute.setSort(a+1);
            qyCommodityAttributeService.save(bute);
        }

        return Result.OK();
    }

    @Override
    public Result<String> updateComodity(QyCommodity commodity){
        List<QyCommodityAttribute> newList = commodity.getCommodityAttributeList();
        if(CollectionUtils.isEmpty(newList)){
            return Result.ERROR("提交信息不全");
        }
        if(commodity.getCommodityStatus()==0){
            if(commodity.getCommodityType()==1){
                //一物一码
                commodity.setOneCodeNum(10000);
                commodity.setOneCodeTotalNum(10000);
                commodity.setMuchCodeNum(null);
                commodity.setMuchCodeTotalNum(null);
            }else{
                commodity.setMuchCodeNum(1);
                commodity.setMuchCodeTotalNum(1);
                commodity.setOneCodeNum(null);
                commodity.setOneCodeTotalNum(null);
            }
        }

        boolean isUp = updateById(commodity);
        if(isUp){
            //查询出所有保存过的属性
            List<QyCommodityAttribute> oldButeList = qyCommodityAttributeService.list(new QueryWrapper<QyCommodityAttribute>()
                    .eq("commodity_id",commodity.getId()).orderByAsc("sort"));
            List<QyCommodityAttribute> tempList = new ArrayList<>();
            HashMap<String,QyCommodityAttribute> hamap = new HashMap<>();
            for(QyCommodityAttribute bute : newList){
                if(StringUtils.isNotEmpty(bute.getId())){
                    hamap.put(bute.getId(),bute);
                }else{
                    tempList.add(bute);
                }
            }
            //保存商品属性
            int idx = 1;
            for(QyCommodityAttribute bute:oldButeList){
                //包含的话就修改
                if(hamap.containsKey(bute.getId())){
                    bute.setSort(idx);
                    qyCommodityAttributeService.updateById(hamap.get(bute.getId()));
                    idx++;
                }else{
                    //不包含的情况 删除
                    qyCommodityAttributeService.removeById(bute.getId());
                }
            }

            //保存新增
            for(QyCommodityAttribute bute:tempList){
                bute.setSort(idx);
                bute.setCommodityId(commodity.getId());
                qyCommodityAttributeService.save(bute);
                idx++;
            }

        }
        return Result.OK();
    }


    @Override
    public QyCommodity getComodity(String id,String companyId){
        QyCommodity commodity;
        if(StringUtils.isNotEmpty(id)){
            commodity = getById(id);
        }else{
            commodity = getOne(new QueryWrapper<QyCommodity>().eq("company_id",companyId).eq("commodity_status",0));
        }
        if(commodity!=null){
            //查询出所有保存过的属性
            List<QyCommodityAttribute> buteList = qyCommodityAttributeService.list(new QueryWrapper<QyCommodityAttribute>()
                    .eq("commodity_id",commodity.getId()).orderByAsc("sort"));
            commodity.setCommodityAttributeList(buteList);
        }
        return commodity;
    }


    @Override
    public IPage<SourceDataVo> findSourceDataList(SourceDataVo vo,int pageNo,int pageSize){
        QueryWrapper<SourceDataVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("qc.company_id",vo.getCompanyId());
        queryWrapper.eq("qc.commodity_status",1);
        if(StringUtils.isNotEmpty(vo.getCommodityName())){
            queryWrapper.like("qc.commodity_name",vo.getCommodityName());
        }
        queryWrapper.orderByDesc("qc.create_time");
        queryWrapper.groupBy("qc.id");
        IPage<SourceDataVo> page = baseMapper.selectSourcerDataList(new Page<>(pageNo,pageSize),queryWrapper);

        if(CollectionUtils.isNotEmpty(page.getRecords())){
            for(SourceDataVo svo:page.getRecords()){
                Integer userNum = baseMapper.countUserNum(new QueryWrapper<>().eq("cc.commodity_id",svo.getId()));
                userNum = userNum==null?0:userNum;
                svo.setUserNum(userNum);
            }
        }
        return page;
    }

    @Override
    public IPage<VisitUserVo> findVisitUserList(VisitUserVo vo,int pageNo,int pageSize){
        QueryWrapper<VisitUserVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cc.commodity_id",vo.getCommodityId());
        queryWrapper.orderByDesc("cu.create_time");
        if(StringUtils.isNotEmpty(vo.getNickName())){
            queryWrapper.like("cu.nick_name",vo.getNickName());
        }
        if(StringUtils.isNotEmpty(vo.getPhone())){
            queryWrapper.like("cu.phone",vo.getPhone());
        }
        queryWrapper.groupBy("cu.id");
        return baseMapper.selectCuUserList(new Page<>(pageNo,pageSize),queryWrapper);
    }

    @Override
    public Result<?> findUsersSpecils(String commodityId,int pageNo,int pageSize){
        QueryWrapper eWrapper = new QueryWrapper();
        eWrapper.eq("cc.commodity_id",commodityId);
        eWrapper.groupBy("cu.sex");
        return Result.OK(baseMapper.selectUserSpecals(new Page<>(pageNo,pageSize),eWrapper));
    }

    @Override
    public Result<?> findUsersProvince(String commodityId,int pageNo,int pageSize){
        QueryWrapper eWrapper = new QueryWrapper();
        eWrapper.eq("cc.commodity_id",commodityId);
        eWrapper.groupBy("cu.province");
        eWrapper.orderByDesc("COUNT(DISTINCT cu.id)");
        return Result.OK(baseMapper.selectUserSpecals(new Page<>(pageNo,pageSize),eWrapper));
    }

    @Override
    public Result<?> findUsersProvinceCity(String commodityId,String province,int pageNo,int pageSize){
        QueryWrapper eWrapper = new QueryWrapper();
        eWrapper.eq("cc.commodity_id",commodityId);
        eWrapper.eq("cu.province",province);
        eWrapper.groupBy("cu.city");
        eWrapper.orderByDesc("COUNT(DISTINCT cu.id)");
        return Result.OK(baseMapper.selectUserSpecals(new Page<>(pageNo,pageSize),eWrapper));
    }

    @Override
    public Result<?> findUsersVisitDevice(String commodityId,int pageNo,int pageSize){
        QueryWrapper eWrapper = new QueryWrapper();
        eWrapper.eq("cc.commodity_id",commodityId);
        eWrapper.groupBy("cc.visit_device");
        eWrapper.orderByDesc("COUNT(DISTINCT cu.id)");
        return Result.OK(baseMapper.selectUserSpecals(new Page<>(pageNo,pageSize),eWrapper));
    }

}
